package util;

import bean.Pople;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.apache.poi.ss.formula.functions.T;
import org.junit.Test;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cxt
 * @date 2020/9/1
 */
public class JsonUtil {

    /**
     * 处理复杂型JSON
     *
     * 对应 JavaBean
     */
    @Test
    public void test4()
    {
        String jsonString = "{\"name\":\"张员外\",\"age\":\"44\",\"like\":{\"deliciousFood\":\"丸子\",\"number\":\"一碗\",\"girl\":\"小夫人\",\"girlName\":\"倾城\"},\"money\":[\"土地\",\"树林\",\"商铺\"],\"staff\":{\"name\":\"赵六\",\"position\":\"护卫\",\"charactor\":\"肥胖\"}}";
        Pople p = JSON.parseObject(jsonString, Pople.class);
        System.out.println(p);
    }

    @Test
    public void test(){
        String str = "{\"success\":\"true\",\"returnAddress\":\"123\"}";
        JSONObject jsonObject=JSON.parseObject(str);
        String returnAddress = jsonObject.getString("success");
        System.out.println(returnAddress);
    }


    public static T getPerson(String jsonstring, Class cls) {
        T t = null;
        try {
            t = JSON.parseObject(jsonstring, (Type) cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;
    }


    public static List getPersonList(String jsonstring, Class cls) {
        List list = new ArrayList();
        try {
            list = JSON.parseArray(jsonstring, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }

    /**
     * 生成json字符串
     */
    public static String createJson(Object obj) {
        Gson gson = new Gson();
        return gson.toJson(obj);
    }

}
